package com.tao.plan.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.tao.plan.common.BaseThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: Jwt工具类，生成JWT和认证
 */

@Component
@Slf4j
public class JwtUtil {


    /**
     * 密钥
     */
    @Value("askjediowadOIQWUYEOIJASDNo9q37409qwjrd")
    private String SECRET;

    /**
     * 过期时间,单位为秒
     **/
    @Value("15552000")
    private Long EXPIRATION;

    /**
     * 生成token,设置token超时时间, 基于传入的map进行基本数据的设置
     */
    public String createToken(Map<String,String> params) {
        //过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 1000);
        //构建请求头
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        //将信息传入请求头
        JWTCreator.Builder builder = JWT.create()
                .withHeader(map);
        //遍历传入的map，设置到claim中
        params.keySet().forEach(k->{
            //可以将基本信息放到claims中
            builder.withClaim(k,params.get(k));
        });
        String token = builder
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        String uid = BaseThreadLocal.getUid();
        log.info("token生成,uid : {}", uid);
        return token;
    }

    /**
     * 校验token并解析token
     */
    public Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
            log.info("token解码成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("token解码异常");
            //解码异常则抛出异常
            return null;
        }
        return jwt.getClaims();
    }
}

